//
//  JKEmoticonViewController.swift
//  Swift表情键盘
//
//  Created by 王冲 on 2018/1/15.
//  Copyright © 2018年 希爱欧科技有限公司. All rights reserved.
//

import UIKit

private let JKEmoticonViewReuseIdentifier = "JKEmoticonViewReuseIdentifier"
class JKEmoticonViewController: UIViewController {

    // 定义一个闭包属性，用来传递选中的表情模型
    var emoticonDidSelectedCallBack: (_ emoticon: JKEmoticon) ->()
    
    init(callBack: @escaping (_ emoticon: JKEmoticon) ->()) {
        
        self.emoticonDidSelectedCallBack = callBack
        
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

         view.backgroundColor = UIColor.JKRandomColor()
       
         setUI()
    }
    
    // MARK: UI布局
    func setUI() {
        
        // 1.添加视图
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        // 2.控件布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        // 提示： 如果自己想封装一个框架，那么最好不要依赖于其他的框架
        var cons = [NSLayoutConstraint]()
        let dict = ["collectionView": collectionView, "toolbar": toolbar] as [String : Any]
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(cons)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private lazy var collectionView: UICollectionView = {
        
         let clv = UICollectionView(frame: CGRect.zero, collectionViewLayout: JKEmoticonViewFlowLayout())
        clv.backgroundColor = UIColor.yellow
        // 注册cell
        clv.register(JKEmoticonViewCell.self, forCellWithReuseIdentifier: JKEmoticonViewReuseIdentifier)
        clv.dataSource = self
        clv.delegate = self
        return clv
        
    }()
    
    private lazy var toolbar: UIToolbar = {
        
        let bar = UIToolbar()
        bar.backgroundColor = UIColor.purple
        bar.tintColor = UIColor.JKTextGayColor()
        var items = [UIBarButtonItem]()
        
        var index = 0
        for tittle in ["最近","默认","emoji","浪小花"]
        {
            let item = UIBarButtonItem(title: tittle, style: UIBarButtonItemStyle.plain, target: self, action: #selector(JKEmoticonViewController.emoticonClick(btn:)))
            
            item.tag = index
            index = index+1
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        bar.items = items
        
       return bar
    }()
    
    lazy var packages: [JKEmoticonPackage] = JKEmoticonPackage.packageslist
    
    // MARK: 表情键盘的点击事件
    @objc func emoticonClick(btn: UIBarButtonItem) {
        
        print("tag=\(btn.tag)")
        
        collectionView.scrollToItem(at: IndexPath.init(item: 0, section: btn.tag), at: UICollectionViewScrollPosition.left, animated: true)
    }

}

extension JKEmoticonViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    
    // 告诉系统有多少组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return packages.count
    }
    
    /// 告诉系统每组有多少行
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return packages[section].emoticons?.count ?? 0
    }
    /// 告诉系统每组显示什么内容
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JKEmoticonViewReuseIdentifier, for: indexPath) as! JKEmoticonViewCell
        
        // 1.取出对应的数组
        let package = packages[indexPath.section]
        // 2.取出数组对应的模型
        let emoticon = package.emoticons![indexPath.item]
        // 3.赋值给cell
        cell.emoticon = emoticon
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        print(indexPath.item)
        
        // 1.处理最近表情, 将当前使用的表情添加到最近表情的数组中
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        emoticon.times = emoticon.times + 1
        packages[0].appendEmoticons(emoticon: emoticon)
        // collectionView.reloadSections(NSIndexSet(index: 0))
        
        // 2.回调通知使用者当前点击了那个表情
        emoticonDidSelectedCallBack(emoticon)
        
    }
}

private class JKEmoticonViewCell: UICollectionViewCell{
    
    // 表情的赋值
    var emoticon: JKEmoticon?
    {
        didSet{
            
            // 1、判断是否是图片表情
            if emoticon?.chs == nil {
                
                // 防止重用
                iconButton .setImage(nil, for: UIControlState.normal)
                
            }else{
                
                print("emoticon?.chs=\(String(describing: emoticon!.chs))")
                iconButton .setImage(UIImage(named: emoticon!.imagePath!), for: UIControlState.normal)
              
            }
            // 2、设置emoji表情
            // 加上 ?? 防止重用（图片和文字的叠加）
            iconButton.setTitle(emoticon?.emojiStr ?? "", for: UIControlState.normal)
            
            // 3.判断是不是删除按钮
            if emoticon!.isRemoveButton {
                
                iconButton.setImage(UIImage(named: "compose_emotion_delete"), for: UIControlState.normal)
                iconButton.setImage(UIImage(named: "compose_emotion_delete"), for: UIControlState.highlighted)
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setcellUI()
    }
    
    // MARK: 重写UI
    func setcellUI()  {
        
        contentView.addSubview(iconButton)
        iconButton.frame = contentView.bounds.insetBy(dx: 4, dy: 4)
        iconButton.backgroundColor = UIColor.JKRandomColor()
        iconButton.isUserInteractionEnabled = false
    }
    
    lazy var iconButton: UIButton = {
        
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 32);
        return btn
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: 自定义布局
private class JKEmoticonViewFlowLayout: UICollectionViewFlowLayout{
    
    override func prepare() {
        
        // 1.设置cell相关
        let width = collectionView!.bounds.width / 7
        itemSize = CGSize(width: width, height: width)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.horizontal
        // 2.设置collectionView的相关属性
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        //3.注意:最好不要乘以0.5, 因为CGFloat不准确, 所以如果乘以0.5在iPhone4/4身上会有问题
        let y = (collectionView!.bounds.height - 3*width)*0.45
        collectionView?.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
    }
}




